package com.zyl.lock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author zhaoyl
 * @date 2024/5/20 22:05
 * @description 说明  自定义自旋锁
 *
 * 自旋锁
 * 在Java中，自旋锁是指尝试获取锁的线程不会立即阻塞，而是采用循环的方式去尝试获取锁，
 * 这样的好处是减少线程上下文切换的消耗，缺点是循环会消耗CPU。
 */
public class SpinlockDemo {

    AtomicReference<Thread> atomicReference = new AtomicReference<>();
    //加锁
    public void mylock(){
        Thread thread = Thread.currentThread();
        System.out.println("加锁-"+thread.getName()+"==>mylock");
        //自旋锁
        while (!atomicReference.compareAndSet(null,thread)){

        }
        System.out.println(thread.getName()+"加锁OK");
    }

    //解锁
    public void myUnlock(){
        Thread thread = Thread.currentThread();
        System.out.println("解锁-"+thread.getName()+"==>myUnlock");
        atomicReference.compareAndSet(thread,null);
        System.out.println(thread.getName()+"解锁OK");
    }

}
